<template>
  <div class="user-management">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名/邮箱"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="roleFilter" placeholder="角色" clearable @change="handleSearch">
          <el-option label="普通用户" value="user" />
          <el-option label="管理员" value="admin" />
        </el-select>
        <el-select v-model="statusFilter" placeholder="状态" clearable @change="handleSearch">
          <el-option label="正常" value="active" />
          <el-option label="禁用" value="disabled" />
        </el-select>
      </div>
      <div class="action-bar">
        <el-button type="primary" @click="handleBatchEnable" :disabled="!selectedUsers.length">
          <el-icon><Check /></el-icon>启用
        </el-button>
        <el-button type="danger" @click="handleBatchDisable" :disabled="!selectedUsers.length">
          <el-icon><Close /></el-icon>禁用
        </el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <el-table
      v-loading="loading"
      :data="users"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column label="用户信息" min-width="200">
        <template #default="{ row }">
          <div class="user-info">
            <el-avatar :size="40" :src="getFullUrl(row.avatar)" />
            <div class="user-details">
              <div class="username">{{ row.username }}</div>
              <div class="email">{{ row.email }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="头像" width="80">
        <template #default="{ row }">
           <el-avatar :size="40" :src="getFullUrl(row.avatar)" />
          </template>
        </el-table-column>

      <el-table-column label="角色" width="120">
        <template #default="{ row }">
          <el-tag :type="row.role === 'admin' ? 'danger' : 'info'">
            {{ row.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
            {{ row.status === 'active' ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="注册时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column label="最后登录" width="180">
        <template #default="{ row }">
          {{ formatDate(row.lastLoginAt) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button
              type="primary"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              :type="row.status === 'active' ? 'danger' : 'success'"
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleResetPassword(row)"
            >
              重置密码
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editingUser._id ? '编辑用户' : '新增用户'"
      width="500px"
    >
      <el-form
        ref="editFormRef"
        :model="editingUser"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editingUser.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editingUser.email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editingUser.role">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editingUser.status">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Search, Check, Close } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/services/axios'
import { formatDate } from '@/utils/formatters'

// 获取后端基础 URL
const backendUrl = import.meta.env.VITE_BACKEND_URL || window.location.origin;

// 获取完整URL
const getFullUrl = (path) => {
  if (!path) return '/default-avatar.png'
  if (path.startsWith('http')) return path
  // 使用后端 URL 作为基础 URL 来拼接路径
  const relativePath = path.startsWith('/') ? path : `/${path}`;
  return `${backendUrl}${relativePath}`
}

// 查询参数
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')

// 表格数据
const users = ref([])
const loading = ref(false)
const selectedUsers = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 编辑对话框
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const saving = ref(false)
const editingUser = ref({
  username: '',
  email: '',
  role: 'user',
  status: 'active'
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      search: searchQuery.value,
      role: roleFilter.value,
      status: statusFilter.value
    }
    const response = await axios.get('/api/admin/users', { params })
    users.value = response.data.users
    total.value = response.data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 批量启用
const handleBatchEnable = async () => {
  try {
    await ElMessageBox.confirm('确定要启用选中的用户吗？')
    const userIds = selectedUsers.value.map(user => user._id)
    await axios.post('/api/admin/users/batch-enable', { userIds })
    ElMessage.success('启用成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量启用失败:', error)
      ElMessage.error('批量启用失败')
    }
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  try {
    await ElMessageBox.confirm('确定要禁用选中的用户吗？')
    const userIds = selectedUsers.value.map(user => user._id)
    await axios.post('/api/admin/users/batch-disable', { userIds })
    ElMessage.success('禁用成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量禁用失败:', error)
      ElMessage.error('批量禁用失败')
    }
  }
}

// 编辑用户
const handleEdit = (user) => {
  editingUser.value = { ...user }
  editDialogVisible.value = true
}

// 保存用户
const handleSaveUser = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        console.log('正在保存用户:', editingUser.value); // 添加调试信息
        
        // 简化请求，使用原始JSON数据
        const userData = {
          username: editingUser.value.username,
          email: editingUser.value.email,
          role: editingUser.value.role,
          status: editingUser.value.status
        };
        
        console.log('发送用户数据:', userData);
        
        // 修改API路径，确保使用正确的后端路径
        const apiPath = editingUser.value._id 
          ? `/api/admin/users/${editingUser.value._id}/update`  // 修改为正确的更新路径
          : '/api/admin/users/create';  // 修改为正确的创建路径
        
        let response;
        try {
          console.log('尝试使用POST方法 - 统一使用POST');
          response = await axios.post(apiPath, userData);
        } catch (error) {
          console.error('POST请求失败', error);
          throw error;
        }
        
        console.log('保存用户响应:', response.data); // 添加调试信息
        ElMessage.success('更新成功');
        editDialogVisible.value = false;
        fetchUsers();
      } catch (error) {
        console.error('保存用户失败:', error.response?.data || error);
        ElMessage.error(error.response?.data?.message || '保存用户失败，请检查网络连接或API路径');
      } finally {
        saving.value = false;
      }
    }
  });
};

// 切换用户状态
const handleToggleStatus = async (user) => {
  const action = user.status === 'active' ? '禁用' : '启用';
  try {
    await ElMessageBox.confirm(`确定要${action}该用户吗？`);
    console.log(`正在${action}用户:`, user._id); // 添加调试信息
    
    // 尝试不同的API路径
    const apiPath = `/api/admin/users/${user._id}/status`;
    const newStatus = user.status === 'active' ? 'disabled' : 'active';
    
    const response = await axios.put(apiPath, {
      status: newStatus
    });
    
    console.log(`${action}用户响应:`, response.data); // 添加调试信息
    ElMessage.success(`${action}成功`);
    user.status = newStatus; // 更新本地状态
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${action}用户失败:`, error.response?.data || error);
      ElMessage.error(error.response?.data?.message || `${action}失败`);
    }
  }
};

// 重置密码
const handleResetPassword = async (user) => {
  try {
    await ElMessageBox.confirm('确定要重置该用户的密码吗？');
    console.log('正在重置密码:', user._id); // 添加调试信息
    
    const response = await axios.post(`/api/admin/users/${user._id}/reset-password`);
    console.log('重置密码响应:', response.data); // 添加调试信息
    
    ElMessage.success(response.data?.message || '密码重置成功');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error.response?.data || error);
      ElMessage.error(error.response?.data?.message || '重置密码失败');
    }
  }
};

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

// 初始化
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
}

.search-bar .el-input {
  width: 200px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: bold;
}

.email {
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>